<template>
  <div class="main">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="160px"
      class="form"
    >
      <el-form-item
        label="作品名称"
        prop="name"
      >
        <el-input v-model="form.name" />
      </el-form-item>

      <el-form-item
        label="作品作者"
        prop="author"
      >
        <el-input v-model="form.author" />
      </el-form-item>

      
      <el-form-item
        label="作品封面"
        prop="cover"
      >
        <div
          style="width:148px;height:148px"
          v-if="form.cover"
        >
          <img
            class="el-upload-list__item-thumbnail"
            :src="formCover"
            alt=""
            style="object-fit:contain;width:100%;height:100%"
          >
        </div>
        
        <el-upload
          ref="imgUpload"
          :action="uploadUrl"
          list-type="picture-card"
          :auto-upload="true"
          :on-success="coverUploadSuccess"
          :limit='1'
          :show-file-list="false"

          accept=".jpg,.jpeg,.png,.pdf,.JPG,.JPEG,.PBG"
        >
          <i
            slot="default"
            class="el-icon-plus"
          ></i>
          <!-- <div
            slot="file"
            style="width:100%;height:100%"
            v-if="form.cover"
            slot-scope="{file}"
          >
            <img
              
              class="el-upload-list__item-thumbnail"
              :src="formCover"
              alt=""
              style="object-fit:contain;"
            >
          </div> -->
        </el-upload>
      </el-form-item>

      <el-form-item
        label="作品类型"
        prop="classifyId"
      >
        <el-select
          v-model="form.classifyId"
          placeholder="请选择"
        >
          <el-option
            v-for="item in classifyIdArr"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item
        label="是否可在线阅读"
        prop="canReadOnLine"
      >
        <el-radio
          v-model="form.canReadOnLine"
          :label="0"
        >否，必须下载</el-radio>
        <el-radio
          v-model="form.canReadOnLine"
          :label="1"
        >是</el-radio>
      </el-form-item>

      <el-form-item
        label="下载地址"
        prop="path"
        v-if="form.canReadOnLine === 0"
        :rules="{
          required: true, message: '下载地址不能为空', trigger: 'blur'
        }"
      >
        <el-input v-model="form.path" />
      </el-form-item>

      <el-form-item
        label="下载验证码"
        prop="downloadCode"
        v-if="form.canReadOnLine === 0"
      >
        <el-input v-model="form.downloadCode" />
      </el-form-item>

      <el-form-item
        label="写作状态"
        prop="status"
      >
        <el-radio
          v-model="form.status"
          :label="0"
        >连载</el-radio>
        <el-radio
          v-model="form.status"
          :label="1"
        >已完成</el-radio>
      </el-form-item>


      <el-form-item
        label="上架状态"
        prop="isShow"
      >
        <el-radio
          v-model="form.isShow"
          :label="0"
        >下架</el-radio>
        <el-radio
          v-model="form.isShow"
          :label="1"
        >上架</el-radio>
      </el-form-item>

      <el-form-item
        label="作品简介"
        prop="brief"
      >
        <el-input
          type="textarea"
          v-model="form.brief"
          :rows="4"
          placeholder="请输入作品简介"
        />
      </el-form-item>

      <!-- 作品标签不超过30个字，使用顿号分割 -->
      <el-form-item label="作品标签">
        <el-input
          v-model="form.lable"
          placeholder="请输入标签，顿号分割"
        />
      </el-form-item>

      <el-form-item>
        <el-button @click="onSubmit">提交</el-button>
      </el-form-item>
    </el-form>
    <el-dialog :visible.sync="dialogVisible">
      <img
        width="100%"
        :src="dialogImageUrl"
        alt=""
      >
    </el-dialog>
  </div>
</template>

<script>
import { getClassify, saveBook ,updateBook} from "@/api/book.js"

export default {
  name: "Book",
  data() {
    return {
      uploadUrl: process.env.VUE_APP_BASE_API + "/api/uploadBookCover",
      form: {
        name: "",
        author: "",
        cover: "",
        classifyId: "",
        lable: "",
        canReadOnLine:'',
        status: 0,
        isShow: 1,
        brief: "",
        path:'',
        downloadCode:''
      },
      formCover:'',  // 图书封面
      rules: {
        name: [{ required: true, message: "名称不能为空" }],
        author: [{ required: true, message: "不能为空" }],
        cover: [{ required: true, message: "封面不能为空" }],
        classifyId: [{ required: true, message: "分类不能为空" }],
        canReadOnLine: [{ required: true, message: "是否可在线阅读不能为空" }],
        status: [{ required: true, message: "状态不能为空" }],
        brief: [{ required: true, message: "简介不能为空" }]
      },
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: false,
      classifyIdArr: [],
      beEditBookObj:null
    }
  },
  watch:{
    'form.name':{
      handler:function(){
        if(!this.form.path){
          this.$set(this.form,'path','/public/ebook/'+this.form.classifyId+'/'+this.form.name+'.pdf')
        }
      }
    },
    'form.classifyId':{
      handler:function(){
        if(!this.form.path){
          this.$set(this.form,'path','/public/ebook/'+this.form.classifyId+'/'+this.form.name+'.pdf')
        }
      }
    },
    'form.canReadOnLine':{
      handler:function(){
        // 在线阅读，在线阅读就需要上传书籍
        if(this.form.canReadOnLine ===1){
          // this.$set(this.form,'path','')
        }else{
          // 非在线阅读,修改书籍状态为已完成
          this.$set(this.form,'status',1)
        }
      }
    },
    'form.cover':{
      handler:function(val){
        if(val){
          this.formCover = process.env.VUE_APP_BASE_API + val
          console.log('formCover:',this.formCover)
        }
      },
      immediate:true
    }
  },
  created() {
    if(this.$route.query.type === 'edit'){
      // 编辑
      try {
        this.beEditBookObj = JSON.parse(localStorage.getItem('beEditBookObj'))  
      } catch (error) {
        console.log('获取被编辑获取报错')
      }
    }
    if(this.beEditBookObj){
      let formKeys = Object.keys(this.form)
      let tempForm = {}
      for(let key of formKeys){
        tempForm[key] = this.beEditBookObj[key]
      }
      this.form = tempForm
    }
    this.init()

    // console.log('this.$route:',this.$route);
  },
  computed:{
    computedFormCover(){
      console.log('process.env.VUE_APP_BASE_API + this.form.cover:',process.env.VUE_APP_BASE_API + this.form.cover)
      return process.env.VUE_APP_BASE_API + this.form.cover
    }
  },
  methods: {
    // 获取分类
    async init() {
      let classifyResult = await getClassify()
      this.classifyIdArr = classifyResult.data
    },
    coverUploadSuccess(response, file, fileList) {
      if (response.code === 200) {
        console.log(response.data.file)
        this.$set(this.form, "cover",response.data.file)
      } else {
        this.$message.error("图片上传失败")
      }
    },
    initBookData(book){
      console.log('editbook:',book);
    },

    async onSubmit() {
      // 保存图书
      this.$refs.form.validate(async valid => {
        // 校验通过
        if (valid) {
          if(this.beEditBookObj){
            // 编辑书籍
            let res = await updateBook(this.beEditBookObj.id,this.form)
            if (res.code === 0) {
              localStorage.removeItem('beEditBookObj')
              this.$message.success("修改书籍成功")
              this.$router.replace('/library')
            } else {
              this.$message.error(res.msg)
            }
          }else{
            // 新建书籍
            let res = await saveBook(this.form)
            if (res.code === 0) {
              this.$message.success("添加书籍成功")
              this.$refs.form.resetFields()
              this.$refs.imgUpload.clearFiles()
              // console.log('this.form:',this.form);
            } else {
              this.$message.error(res.msg)
            }
          }
          
        }
      })
    },
    onCancel() {
      this.$message({
        message: "cancel!",
        type: "warning"
      })
    },
    handleRemove(file) {
      console.log(file)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleDownload(file) {
      console.log(file)
    }
  }};
</script>

<style scoped>
.form {
  padding-top: 30px;
}
.line {
  text-align: center;
}
</style>

